#include <pspsdk.h>
#include <pspkernel.h>
#include <pspdebug.h>
#include <pspdisplay_kernel.h>
#include <pspsysmem_kernel.h>
#include <stdio.h>
#include <string.h>

PSP_MODULE_INFO("USBDRIVER", PSP_MODULE_KERNEL, 1, 0);

#include "..\states.h"
#define DEBUG(...) { char mitext[500]; sprintf(mitext,__VA_ARGS__); strcat(pdata->text,mitext); }

int getModelKernel(){ 
	k1s; 
	int retVal = sceKernelGetModel(); 
	k1r; 
	return retVal;
}


#include "defines.h"
#include "psfreedom.h"
#include "descriptors.h"
#include "hub.h"
#include "usb.h"


int register_udriver() { k1s; resetdata(pdata); pdata->p = &PS3HubDriver; int ret = sceUsbbdRegister(&PS3HubDriver); k1r; return ret; }
int start_mainusbbus() { return sceUsbStart("USBBusDriver", 0, 0 ); }
int start_mainusbdrv() { return sceUsbStart(PS3HubDriver.driverName, 0, 0 ); }
int activate_usbdriv() { return sceUsbActivate(0xCCCC); }
int drivers_stop_all() { k1s; sceUsbDeactivate(0xCCCC); sceUsbStop(PS3HubDriver.driverName,0,0); sceUsbStop("USBBusDriver",0,0); sceUsbbdUnregister(&PS3HubDriver); k1r; }



void stepperfunction(struct passingdata *ptr) { 
	pdata = ptr;	
	struct psfreedom_device *dev = &psfreed;
	int i;
	
	if (dev->switch_to_port_delayed >= 0) {
		switch_to_port (dev, dev->switch_to_port_delayed);
	}
	dev->switch_to_port_delayed = -1;
	
	switch (estado) {
		case APP_INITING:
			resetdata(pdata);
			sprintf(pdata->text,"USB Driver 0.1a - (c) DeViaNTe\n"); 
			
			/* Config our device */
			dev->current_port = 0;
			for (i = 0; i < 6; i++) { dev->hub_ports[i].status = dev->hub_ports[i].change = 0; }
			for (i = 0; i < 7; i++) { dev->port_address[i] = 0; }
			dev->gadget = &gadgeto;
			gadgeto.dev = dev;
			dev->req = &request;
			dev->hub_req = &hub_request;
			dev->switch_to_port_delayed = -1;
			
			/* estado */
			dev->status = INIT;
			pdata->status = APP_INIT;
			pdata->timeout = 0;
			estado = APP_INIT;
			
			break;
		case APP_INIT:
			pdata->status = APP_READY;
			pdata->timeout = 0;
			estado = APP_READY;
			break;
		case APP_READY:
			if ( dev->status == HUB_READY ) {	// Ya hemos alcanzado este nivelazo.
				pdata->timeout = 250;	//temporizador!
				pdata->status = APP_HUB_READY;
				estado = APP_HUB_READY;
			}		
			break;
		case APP_HUB_READY:
			if ( pdata->timeout == 0 ) {
				hub_connect_port(dev,1);
				dev->status = DEVICE1_WAIT_READY;
				pdata->status = APP_DEV1_WAIT;
				pdata->timeout = 0;
				estado = APP_DEV1_WAIT;
			}
			else { pdata->status = APP_HUB_READY; pdata->timeout = 0; }
			break;
		case APP_DEV1_WAIT:
			
			break;
	}
	
}

/* Init */
int module_start(SceSize args, void *argp) { 
	return 0;
}

int module_stop() { 
	return 0;
}
